/**
*菜单渲染 九宫格
*/

var menuContainer = "<div id=\"menu-box\" class=\"\"></div>";
var menuBox = '<div id="indexMenuBox" class="col-sm-8 col-sm-offset-2 infobox-container "></div>';
var rowMenuNum = 3;//每行数量 -1:自适应

function initMenu() {
	try {
		createMenu();
	} catch (e) {
		alert('菜单加载出错...');
	}
}

function addBox(){
	$("#menu-box-container").append(menuContainer);
}

function getBox() {
	var $box = $("#menu-box");
	if(!$box || $box.length <= 0){
		addBox();
		$box = $("#menu-box");
	}
	return $box;
}

function getMenuBox() {
	return $("#indexMenuBox");
}

function createMenu() {
	getBox().html(menuBox);
	var $box = getMenuBox();
	if(!fnArray || fnArray.length <= 0){
		alert("菜单加载失败,菜单列表fnArray无效");
		return false;
	}
	var ratio = Math.round(100 / rowMenuNum);//计算每个菜单所占比例(百分之)
	var ratioCnt = 0;//当前所占比例总和
	var $menuRow = {};
	var styleObj = {
			"background" : "white",
			"color" : "black",
			"float" : "left",
			"font-size" : "14px",
			"padding" : "20px 0",
			"font-size" : "14px"
	};
	for (var i = 0; i < fnArray.length; i++) {
		//新行
		if(i % rowMenuNum == 0){
			var rowId = 'sudoku-menu-row-'+ (i / rowMenuNum + 1);
			$box.append('<div id="'+ rowId +'" class="sudoku-menu-row shuffling-figure clear-padding-left clear-padding-right"></div>');
			$menuRow = $("#" + rowId);
			
			ratioCnt = 0;//新行比例清零
		}
		
		//如果是每一行最后一个
		if(i % rowMenuNum == rowMenuNum - 1){
			styleObj["width"] = (100 - ratioCnt) + "%";
			styleObj["border-right"] = "0px";
		}else{
			styleObj["width"] = ratio + "%";
			styleObj["border-right"] = "solid 1px #f2f2f2";
		}
		//如果是最后一行
		if(Math.ceil((i + 1) / rowMenuNum) == Math.ceil(fnArray.length / rowMenuNum)){
			styleObj["border-bottom"] = "0px";
		}else{
			styleObj["border-bottom"] = "solid 1px #f2f2f2";
		}
		ratioCnt += ratio;
		var menu = fnArray[i];
		if (!menu['data']['id']) {
			menu['data']['id'] = (fnArray[i]['data']['id'] = 'idx-menu-' + i);
		}
		var imgSrc = menu['sudoku']['src'];
		var menuHtm='';
		//虚拟节点
		if(menu['type'] === 'virtual'){
			styleObj["padding"] = "35px 0";
			menuHtm='\
				<div id="'+menu['data']['id']+'" class="is-click sudoku-menu-item">\
				'+(menu['data']['text'] || '')+'\
				</div>';
		}else{
			menuHtm='\
				<div id="'+menu['data']['id']+'" class="is-click sudoku-menu-item">\
				<img src="'+imgSrc+'" /><br/>\
				'+(menu['data']['text'] || '')+'\
				</div>';
		}
		$menuRow.append(menuHtm);
		if(menu['click']){
			$("#" + menu['data']['id']).on('click',menu['click']);
		}
		//添加样式
		$("#" + menu['data']['id']).css(styleObj);
	}
}

initMenu();